package com.scut.wordskillerbackend.service;

import com.scut.wordskillerbackend.mapper.UserMapper;
import com.scut.wordskillerbackend.po.User;
import com.scut.wordskillerbackend.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public boolean register(User user) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        user.setPassword(MD5Utils.encodeByMd5(user.getPassword()));
        user.setToken(TokenService.getToken(user.getUsername()));
        return userMapper.insert(user) == 1;
    }

    public User login(User user) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        String password = user.getPassword();
        user.setPassword(MD5Utils.encodeByMd5(user.getPassword()));
        User result = userMapper.selectByUserIdAndPassword(user);
        if (result == null) return null;

        String newToken = TokenService.getToken(user.getUsername());
        if (newToken != null && !newToken.equals(result.getToken())) {
            result.setToken(newToken);
            userMapper.updateById(result);
            return result;
        }
        return result;
    }

    public User updateUser(String password, String token) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        User userFound = selectUserByToken(token);
        if(userFound==null) return null;
        userFound.setPassword(MD5Utils.encodeByMd5(password));
        userFound.setToken(TokenService.getToken(userFound.getUsername()));
        return (userMapper.updateById(userFound) == 1) ? userFound : null;
    }

    public User selectUserByToken(String token){
        return userMapper.selectByToken(token);
    }
}
